//
//  AppDelegate.m
//  Mecca
//
//  Created by Ryan Enguero on 5/20/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
// sad

#import "AppDelegate.h"
#import "UIManager.h"
#import "ParserClass.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <FacebookSDK/FacebookSDK.h>
#import "UserDetails.h"
#import "ListenedSongs.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;





- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    //self.window.backgroundColor = [UIColor whiteColor];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
//    [self deleteAllObjectsInCoreData];
    
    [FBLoginView class];
    [FBProfilePictureView class];
    
    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
  //  [self fetchMusicDataFromCoreData];
    
    //    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //    NSEntityDescription *entity = [NSEntityDescription
    //                                   entityForName:@"DownloadedMusic" inManagedObjectContext:context];
    //    [fetchRequest setEntity:entity];
    //    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    //    for (NSManagedObject *info in fetchedObjects) {
    //        NSLog(@"Name: %@", [info valueForKey:@"name"]);
    //        NSLog(@"Data: %@", [info valueForKey:@"data"]);
    //        //        NSManagedObject *details = [info valueForKey:@"details"];
    //        //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    //    }
    
    self.window.rootViewController = [[UIManager sharedItems] navWithLogin];
    
    [self.window makeKeyAndVisible];
    return YES;
}

//- (void)applicationWillResignActive:(UIApplication *)application
//{
//    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
//    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
//}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
    NSError *error = nil;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"CacheDownloadData" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    
    NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    
    
    for (NSManagedObject *managedObject in items) {
        [_managedObjectContext deleteObject:managedObject];
        // NSLog(@"%@ object deleted",entityDescription);
        
        
    }
    
    if (![context save:&error])
    {
        NSLog(@"Error deleting movie, %@", [error userInfo]);
    }
    
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}




#pragma mark Play Music in background; 

- (void)applicationWillResignActive:(UIApplication *)application{
    UIApplication *app = [UIApplication sharedApplication];
    UIBackgroundTaskIdentifier bgTask = 0;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    //    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"1" ofType:@".mp3"];
    //    NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
    //_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
    [_player setNumberOfLoops:-1];
    //    alarmTimer = [NSTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:@selector(playAlarm) userInfo:nil repeats:NO];
    [_player prepareToPlay];
    [_player play];
}


#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Mecca" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Mecca.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

- (void)musicDataWithName:(NSString*)name andData:(NSData*)data andSongID:(NSString*)songID andImage:(NSString*)imgAlbum andDuration:(NSString*)songDuration andArtistName:(NSString*)artistName anduserID:(NSString*)userID andAlbumName:(NSString*)albumName andSongLyrics:(NSString*)lyrics{
    
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *musicDownloaded = [NSEntityDescription
                                        insertNewObjectForEntityForName:@"DownloadedMusic"
                                        inManagedObjectContext:context];
    
    [musicDownloaded setValue:userID forKey:@"userID"];
    [musicDownloaded setValue:songID forKey:@"id"];
    [musicDownloaded setValue:name forKey:@"name"];
    [musicDownloaded setValue:data forKey:@"data"];
    [musicDownloaded setValue:songDuration forKey:@"duration"];
    [musicDownloaded setValue:imgAlbum forKey:@"image"];
    [musicDownloaded setValue:artistName forKey:@"artistName"];
    [musicDownloaded setValue:albumName forKey:@"albumName"];
    [musicDownloaded setValue:lyrics forKey:@"lyrics"];
    
    
    //    NSManagedObject *failedBankDetails = [NSEntityDescription
    //                                          insertNewObjectForEntityForName:@"FailedBankDetails"
    //                                          inManagedObjectContext:context];
    //    [failedBankDetails setValue:[NSDate date] forKey:@"closeDate"];
    //    [failedBankDetails setValue:[NSDate date] forKey:@"updateDate"];
    //    [failedBankDetails setValue:[NSNumber numberWithInt:12345] forKey:@"zip"];
    //    [failedBankDetails setValue:failedBankInfo forKey:@"info"];
    //    [failedBankInfo setValue:failedBankDetails forKey:@"details"];
    
    NSError *error;
    
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    
    
    //            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //            NSEntityDescription *entity = [NSEntityDescription
    //                                           entityForName:@"DownloadedMusic" inManagedObjectContext:context];
    //            [fetchRequest setEntity:entity];
    //            NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    //            for (NSManagedObject *info in fetchedObjects) {
    //                NSLog(@"Name: %@", [info valueForKey:@"name"]);
    //                NSLog(@"Data: %@", [info valueForKey:@"data"]);
    //                //        NSManagedObject *details = [info valueForKey:@"details"];
    //                //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    //            }
    
}

- (void)fetchMusicDataFromCoreData{
    
    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"DownloadedMusic" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    
   
    arrData = [NSMutableArray array];
    
    for (NSManagedObject *info in fetchedObjects) {
        
        if ([[info valueForKey:@"userID"] isEqualToString:[userDetails idUser]]) {
            dictData = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[info valueForKey:@"userID"], @"userID",[info valueForKey:@"id"], @"id", [info valueForKey:@"name"], @"name", [info valueForKey:@"data"], @"data", [info valueForKey:@"image"], @"image",[info valueForKey:@"duration"], @"duration" , [info valueForKey:@"artistName"], @"artistName", [info valueForKey:@"albumName"], @"albumName", [info valueForKey:@"lyrics"], @"lyrics",nil];
            
            [arrData addObject:dictData];
            
            // NSLog(@"info: %@", arrData);
            
            [[ParserClass sharedItems] downloadedSongWithID:arrData];
        }
       // NSLog(@"Data: %@", [info valueForKey:@"data"]);
        //        NSManagedObject *details = [info valueForKey:@"details"];
        //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    }
    
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


#pragma mark Facebook Methods;


//Third Code

//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation {
//    
//    // Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
//    BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
//    
//    // You can add your app-specific url handling code here if needed
//    
//    return wasHandled;
//}




//Seccond Code

//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation {
//    
//    BOOL urlWasHandled =
//    [FBAppCall handleOpenURL:url
//           sourceApplication:sourceApplication
//             fallbackHandler:
//     ^(FBAppCall *call) {
//         // Parse the incoming URL to look for a target_url parameter
//         NSString *query = [url query];
//         NSDictionary *params = [self parseURLParams:query];
//         // Check if target URL exists
//         NSString *appLinkDataString = [params valueForKey:@"al_applink_data"];
//         if (appLinkDataString) {
//             NSError *error = nil;
//             NSDictionary *applinkData =
//             [NSJSONSerialization JSONObjectWithData:[appLinkDataString dataUsingEncoding:NSUTF8StringEncoding]
//                                             options:0
//                                               error:&error];
//             if (!error &&
//                 [applinkData isKindOfClass:[NSDictionary class]] &&
//                 applinkData[@"target_url"]) {
//                 self.refererAppLink = applinkData[@"referer_app_link"];
//                 NSString *targetURLString = applinkData[@"target_url"];
//                 // Show the incoming link in an alert
//                 // Your code to direct the user to the
//                 // appropriate flow within your app goes here
//                 [[[UIAlertView alloc] initWithTitle:@"Received link:"
//                                             message:targetURLString
//                                            delegate:nil
//                                   cancelButtonTitle:@"OK"
//                                   otherButtonTitles:nil] show];
//             }
//         }
//     }];
//    
//    return urlWasHandled;
//}
//
//// A function for parsing URL parameters
//- (NSDictionary*)parseURLParams:(NSString *)query {
//    NSArray *pairs = [query componentsSeparatedByString:@"&"];
//    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
//    for (NSString *pair in pairs) {
//        NSArray *kv = [pair componentsSeparatedByString:@"="];
//        NSString *val = [[kv objectAtIndex:1]
//                         stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        [params setObject:val forKey:[kv objectAtIndex:0]];
//    }
//    return params;
//}



//First code

// In order to process the response you get from interacting with the Facebook login process,
// you need to override application:openURL:sourceApplication:annotation:
//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation {
//    
//    // Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
//    BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
//    
//    // You can add your app-specific url handling code here if needed
//    
//    return wasHandled;
//}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    BOOL urlWasHandled =
    [FBAppCall handleOpenURL:url
           sourceApplication:sourceApplication
             fallbackHandler:
     ^(FBAppCall *call) {
         // Parse the incoming URL to look for a target_url parameter
         NSString *query = [url query];
         NSDictionary *params = [self parseURLParams:query];
         // Check if target URL exists
         NSString *appLinkDataString = [params valueForKey:@"al_applink_data"];
         if (appLinkDataString) {
             NSError *error = nil;
             NSDictionary *applinkData =
             [NSJSONSerialization JSONObjectWithData:[appLinkDataString dataUsingEncoding:NSUTF8StringEncoding]
                                             options:0
                                               error:&error];
             if (!error &&
                 [applinkData isKindOfClass:[NSDictionary class]] &&
                 applinkData[@"target_url"]) {
                 self.refererAppLink = applinkData[@"referer_app_link"];
                 NSString *targetURLString = applinkData[@"target_url"];
                 // Show the incoming link in an alert
                 // Your code to direct the user to the
                 // appropriate flow within your app goes here
                 [[[UIAlertView alloc] initWithTitle:@"Received link:"
                                             message:targetURLString
                                            delegate:nil
                                   cancelButtonTitle:@"OK"
                                   otherButtonTitles:nil] show];
             }
         }
     }];
    
    return urlWasHandled;
}

// A function for parsing URL parameters
- (NSDictionary*)parseURLParams:(NSString *)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val = [[kv objectAtIndex:1]
                         stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [params setObject:val forKey:[kv objectAtIndex:0]];
    }
    return params;
}

- (void)getSongListenedWithName:(NSString*)songName andUserID:(NSString*)userID{

    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *songListened = [NSEntityDescription
                                        insertNewObjectForEntityForName:@"ListenedSong"
                                        inManagedObjectContext:context];
    
    
    [songListened setValue:songName forKey:@"songName"];
    [songListened setValue:userID forKey:@"userID"];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
}

- (void)fetchListenedSong{
    
    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"ListenedSong" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    
    
    arrData = [NSMutableArray array];
    
    for (NSManagedObject *info in fetchedObjects) {
        
                if ([[info valueForKey:@"userID"] isEqualToString:[userDetails idUser]]) {
        dictData = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[info valueForKey:@"songName"], @"songName",[info valueForKey:@"userID"], @"userID",nil];
        
        [arrData addObject:dictData];
        
        // NSLog(@"info: %@", arrData);
        
        [[ParserClass sharedItems] getListenedSongs:arrData];
                    
                    
                }
        // NSLog(@"Data: %@", [info valueForKey:@"data"]);
        //        NSManagedObject *details = [info valueForKey:@"details"];
        //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    }
    
}



- (void)downloadingDataWithName:(NSString*)name andArtist:(NSString*)artistName andDuration:(NSString*)duration andImage:(NSString*)imgAlbum andPrice:(NSString*)price andSongID:(NSString*)songID andAlbumName:(NSString*)albumName andSongLyrics:(NSString*)lyrics{
    
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *musicDownloaded = [NSEntityDescription
                                        insertNewObjectForEntityForName:@"CacheDownloadData"
                                        inManagedObjectContext:context];
    
    [musicDownloaded setValue:name forKey:@"songTitle"];
    [musicDownloaded setValue:artistName forKey:@"artistName"];
    [musicDownloaded setValue:duration forKey:@"duration"];
    [musicDownloaded setValue:imgAlbum forKey:@"img"];
    [musicDownloaded setValue:price forKey:@"price"];
    [musicDownloaded setValue:songID forKey:@"songID"];
    [musicDownloaded setValue:albumName forKey:@"albumName"];
     [musicDownloaded setValue:lyrics forKey:@"lyrics"];
//    [musicDownloaded setValue:songData forKey:@"songData"];
    
    //    NSManagedObject *failedBankDetails = [NSEntityDescription
    //                                          insertNewObjectForEntityForName:@"FailedBankDetails"
    //                                          inManagedObjectContext:context];
    //    [failedBankDetails setValue:[NSDate date] forKey:@"closeDate"];
    //    [failedBankDetails setValue:[NSDate date] forKey:@"updateDate"];
    //    [failedBankDetails setValue:[NSNumber numberWithInt:12345] forKey:@"zip"];
    //    [failedBankDetails setValue:failedBankInfo forKey:@"info"];
    //    [failedBankInfo setValue:failedBankDetails forKey:@"details"];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    
    
    //            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //            NSEntityDescription *entity = [NSEntityDescription
    //                                           entityForName:@"DownloadedMusic" inManagedObjectContext:context];
    //            [fetchRequest setEntity:entity];
    //            NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    //            for (NSManagedObject *info in fetchedObjects) {
    //                NSLog(@"Name: %@", [info valueForKey:@"name"]);
    //                NSLog(@"Data: %@", [info valueForKey:@"data"]);
    //                //        NSManagedObject *details = [info valueForKey:@"details"];
    //                //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    //            }
    
}

- (void)fetchDownloadingDataFromCoreData{
    
//    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"CacheDownloadData" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    
    
    arrData = [NSMutableArray array];
    
    for (NSManagedObject *info in fetchedObjects) {
        
//        if ([[info valueForKey:@"userID"] isEqualToString:[userDetails idUser]]) {
            dictData = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[info valueForKey:@"songTitle"], @"songTitle",[info valueForKey:@"artistName"], @"artistName", [info valueForKey:@"duration"], @"duration", [info valueForKey:@"img"], @"img", [info valueForKey:@"price"], @"price", [info valueForKey:@"songID"], @"songID", [info valueForKey:@"albumName"], @"albumName", [info valueForKey:@"lyrics"], @"lyrics",nil];
            
            [arrData addObject:dictData];
            
            // NSLog(@"info: %@", arrData);
            
            [[ParserClass sharedItems] getDownloadingData:arrData];
//        }
        // NSLog(@"Data: %@", [info valueForKey:@"data"]);
        //        NSManagedObject *details = [info valueForKey:@"details"];
        //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    }
    
}


- (void)deleteDownloadingData:(NSInteger)idx{
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
   NSError *error = nil;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"CacheDownloadData" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

    NSManagedObject *objectToBeDeleted = [fetchedObjects objectAtIndex:idx];

    [context deleteObject:objectToBeDeleted];

    
    if (![context save:&error])
    {
    NSLog(@"Error deleting movie, %@", [error userInfo]);
    }
    
}



- (void)playListArtistName:(NSString*)artistName andAlbumName:(NSString*)albumName{
    
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *musicDownloaded = [NSEntityDescription
                                        insertNewObjectForEntityForName:@"PlayList"
                                        inManagedObjectContext:context];
    
    [musicDownloaded setValue:artistName forKey:@"artistName"];
    [musicDownloaded setValue:albumName forKey:@"albumName"];
    

    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    
}

- (void)fetchPlayListDataFromCoreData{
    
    //    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    NSManagedObjectContext *context = [self managedObjectContext];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"PlayList" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    
    
    arrData = [NSMutableArray array];
    
    for (NSManagedObject *info in fetchedObjects) {
        
        //        if ([[info valueForKey:@"userID"] isEqualToString:[userDetails idUser]]) {
        dictData = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[info valueForKey:@"albumName"], @"albumName",[info valueForKey:@"artistName"], @"artistName",nil];
        
        [arrData addObject:dictData];
        
         NSLog(@"info playListData: %@", arrData);
        
        [[ParserClass sharedItems] getPlayListData:arrData];
        
//        [[ParserClass sharedItems] getDownloadingData:arrData];
        //        }
        // NSLog(@"Data: %@", [info valueForKey:@"data"]);
        //        NSManagedObject *details = [info valueForKey:@"details"];
        //        NSLog(@"data: %@", [details valueForKey:@"zip"]);
    }
    
}

@end
